﻿using QxFramework.Core;
using QxFramework.Utilities;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoSingleton<AudioManager>
{
    private Dictionary<string, AudioClip> EffectAudioDictionary;
    private AudioSource[] audioSources;
    private AudioSource bgAudioSource;
    private AudioSource audioSourceEffect;
    public float bgmVolume = 1f;
    public float effectVolume = 1f;
    private int count = -1;
    private string audioResourcePath = "Audio/BGM";//背景音乐的路径
    private string EffectAudioResourcePath = "Audio";
    // Use this for initialization

    void Awake()
    {
        EffectAudioDictionary = new Dictionary<string, AudioClip>();
        AudioClip[] effectAudioArray = Resources.LoadAll<AudioClip>(EffectAudioResourcePath);
        audioSources = Transform.FindObjectsOfType<AudioSource>();
        bgAudioSource = audioSources[0];
        audioSourceEffect = audioSources[1];
        foreach (AudioClip item in effectAudioArray)
        {
            EffectAudioDictionary.Add(item.name, item);
        }

    }

    private void PlayAudio(AudioSource audioSource, AudioClip clip, float volume, bool loop = false)
    {
        audioSource.volume = volume;
        audioSource.loop = loop;
        audioSource.clip = clip;
        audioSource.Play();
    }
    /// <summary>
    /// 播放背景音乐,包括ui的背景音乐
    /// </summary>
    /// <param name="name">音乐片段的文件名</param>  
    public void GraduatePlayBGM()
    {
        if (count == -1) return;
        //Debug.Log("Uptest" + count);
        bgAudioSource.volume += 0.01f;
        count--;
        Invoke("GraduatePlayBGM", 0.3f);
    }
    public void PlayBgAudio(string name, float volum = 1, bool isLoop = true)
    {
        AudioClip clip = ResourceManager.Instance.Load<AudioClip>(audioResourcePath + "/" + name);
        if (clip != null)
        {
            PlayAudio(bgAudioSource, clip, 0f, isLoop);
            count = (int)(volum * bgmVolume * 100);
            GraduatePlayBGM();
        }
            
    }



    /// <summary>
    /// 播放音效
    /// </summary>
    /// <param name="name">音乐片段的文件名</param>
    public void PlayEffectAudio(string name, float volum = 1, bool isLoop = false)
    {
        if (EffectAudioDictionary.ContainsKey(name))
        {
            PlayAudio(audioSourceEffect, EffectAudioDictionary[name], volum * effectVolume, isLoop);
        }
    }
    public void StopCurrentBgm()
    {
        bgAudioSource.Stop();
    }
    public void GraduateStopCurrentBGM()
    {

        if (count == -1)
        {
            count = (int)(bgAudioSource.volume * 100);
        }
        if (count == 0)
        {
            count = -1;
            return;
        }
        Debug.Log("test" + count);
        bgAudioSource.volume -= 0.01f;
        count--;
        Invoke("GraduateStopCurrentBGM", 0.1f);
    }
    

}
